package com.ruoyi.file.controller;
import com.ruoyi.file.utils.PdfToImageUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;

import com.alibaba.excel.annotation.ExcelProperty;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.file.dto.FileAttachmentInfoDto;
import com.ruoyi.file.dto.WarehouseInfoDto;
import com.ruoyi.file.service.IFileAttachmentInfoService;
import com.ruoyi.file.utils.PDFUtil;
import com.ruoyi.file.utils.PathUtil;
import com.ruoyi.file.utils.PdfToImageUtil;
import com.ruoyi.file.vo.FileAttachmentInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Map;

import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
/**
 * 附件信息Controller
 *
 * @author liyuxi
 * @date 2024-05-20
 */
@Api(value = "pdf管理", tags = "pdf接口")
@RestController
@RequestMapping("/pdf")
public class PdfController extends BaseController {
    private static final boolean DBG = false;
    @Autowired
    private IFileAttachmentInfoService fileAttachmentInfoService;
    @ApiOperation("生成PDF并返回给前端浏览器")
    @GetMapping("/preview")
    public ResponseEntity<byte[]> generatePDFAndReturn(@Valid WarehouseInfoDto dto) {
        try {
            String basePath = PathUtil.getPath();
            String htmlTmpFile = basePath + "/resource/template/pdfDemo.html";
            String fontFile = basePath + "/resource/font/simsun.ttc";

            Map<String, Object> dataMap = new HashMap<>();





            dataMap.put("handler", dto.getHandler());
            dataMap.put("handlerPhone", dto.getHandlerPhone());

            dataMap.put("title", dto.getTitle());
            dataMap.put("inNum", dto.getInNum());

            dataMap.put("buyerWeighDate", dto.getBuyerWeighDate());

            dataMap.put("plateNo", dto.getPlateNo());
            dataMap.put("buyerGoodsName", dto.getBuyerGoodsName());

            dataMap.put("buyerTareWeight", dto.getBuyerTareWeight());
            dataMap.put("buyerGrossWeight", dto.getBuyerGrossWeight());
            dataMap.put("buyerNetWeight", dto.getBuyerNetWeight());
            dataMap.put("buyerDeductWeight", dto.getBuyerDeductWeight());


            dataMap.put("buyerPhone", dto.getBuyerPhone());
            dataMap.put("driverName", dto.getDriverName());
            dataMap.put("driverPhone", dto.getDriverPhone());











            dataMap.put("buyerGoodsUnit", dto.getBuyerGoodsUnit());
            dataMap.put("sellerPhone", dto.getSellerPhone());
            dataMap.put("sellerName", dto.getSellerName());



            String htmlTmpStr = PDFUtil.freemarkerRender(dataMap, htmlTmpFile);

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            PDFUtil.createPDF(htmlTmpStr, fontFile, outputStream);

            // 设置HTTP头部
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_TYPE, "application/pdf"); // 设置Content-Type为PDF类型
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"previewed_file.pdf\""); // 设置为inline以便浏览器预览

            return new ResponseEntity<>(outputStream.toByteArray(), headers, HttpStatus.OK);
        } catch (Exception e) {
            throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "生成 PDF 失败", e);
        }
    }


    @ApiOperation("将URL链接内容转换为图片预览（直接在浏览器打开）")
    @GetMapping("/pdfToImage")
    public AjaxResult pdfToImage(
            @RequestParam @NotBlank String url,
            @RequestParam(defaultValue = "lv_order_info") String tableName,
            @RequestParam(defaultValue = "out_weigh_num_img") String colName,
            @RequestParam(defaultValue = "associationId") String associationId
    ) {
        try {
            // 1. 下载PDF文件
            byte[] pdfBytes;
            try (InputStream is = downloadPdf(url);
                 ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
                byte[] buf = new byte[4096];
                int len;
                while ((len = is.read(buf)) != -1) {
                    baos.write(buf, 0, len);
                }
                pdfBytes = baos.toByteArray();
            }

            // 2. PDF转图片字节
            byte[] imageBytes = PdfToImageUtil.pdfFirstPageToImage(new java.io.ByteArrayInputStream(pdfBytes));

            // 3. 构造图片MultipartFile
            MultipartFile imageFile = new MockMultipartFile(
                    "file",
                    "preview.png",
                    "image/png",
                    imageBytes
            );

            // 4. 上传图片
            HashMap<String, Object> result = fileAttachmentInfoService.uploadAttachment(
                    imageFile, tableName, colName, associationId, null);

            return AjaxResult.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("PDF转图片或上传失败: " + e.getMessage());
        }
    }

    // 工具方法：下载PDF
    private InputStream downloadPdf(String urlString) throws Exception {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(20000);
        int code = conn.getResponseCode();
        if (code != 200) {
            throw new RuntimeException("文件下载失败，HTTP状态：" + code);
        }
        String contentType = conn.getContentType();
        if (contentType == null || !contentType.toLowerCase().contains("pdf")) {
            throw new RuntimeException("URL内容不是PDF文件，实际Content-Type：" + contentType);
        }
        return conn.getInputStream();
    }

    @PostMapping("/pdfToImage")
    public AjaxResult pdfToImage(
            @RequestParam("file") MultipartFile file ) {
        try (InputStream is = file.getInputStream()) {
            // 1. PDF转图片
            byte[] imageBytes = PdfToImageUtil.pdfFirstPageToImage(is);

            // 2. 构造图片MultipartFile
            MultipartFile imageFile = new MockMultipartFile(
                    "file",               // 字段名
                    "preview.png",        // 文件名
                    "image/png",          // Content-Type
                    imageBytes            // 内容
            );

            // 3. 调用你的服务
            HashMap<String, Object> stringObjectHashMap   = fileAttachmentInfoService.uploadAttachment(
                    imageFile, "lv_order_info", "out_weigh_num_img", "associationId",  null);

            return AjaxResult.success(stringObjectHashMap);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("PDF转图片或上传失败: " + e.getMessage());
        }
    }


}
